package com.cskaoyan.catmall.typehandler;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.apache.ibatis.type.TypeHandler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 创建日期: 2022/01/07 16:07
 *
 * @author ghr
 */
@MappedTypes(String[].class)
@MappedJdbcTypes(JdbcType.VARCHAR)
public class StringArrayTypeHandler implements TypeHandler<String[]> {
    //jackson
    ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public void setParameter(PreparedStatement preparedStatement, int i, String[] strs, JdbcType jdbcType) throws SQLException {
        //String[] → String
        try {
            String value = objectMapper.writeValueAsString(strs);
            //给对应序号的占位符提供值
            preparedStatement.setString(i, value);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    }

    //String → String[]
    @Override
    public String[] getResult(ResultSet resultSet, String columnName) throws SQLException {
        try {
            String result = resultSet.getString(columnName);
            String[] strs = objectMapper.readValue(result, String[].class);
            return strs;
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return new String[0];
    }

    @Override
    public String[] getResult(ResultSet resultSet, int columnIndex) throws SQLException {
        try {
            String result = resultSet.getString(columnIndex);
            String[] strs = objectMapper.readValue(result, String[].class);
            return strs;
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return new String[0];
    }

    @Override
    public String[] getResult(CallableStatement callableStatement, int i) throws SQLException {
        try {
            String result = callableStatement.getString(i);
            String[] strs = objectMapper.readValue(result, String[].class);
            return strs;
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return new String[0];
    }
}